import cv2
import numpy as np
import glob


# 计算颜色直方图特征向量
def calculate_histogram(image):
    # 计算直方图 [0,1,2] 为RGB通道列表
    hist = cv2.calcHist([image], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])

    # 归一化
    hist = cv2.normalize(hist, hist).flatten()
    return hist


# 加载数据库集中的图片并计算其特征向量
database_images = []
database_features = []

for image_path in glob.glob("./img/data/*.png"):
    image = cv2.imread(image_path)
    image = cv2.resize(image, (256, 256))  # 调整图片大小为统一尺寸
    feature = calculate_histogram(image)
    database_images.append(image)
    database_features.append(feature)

# 加载查询图片并计算其特征向量
# 8（黄脸）、168（文字）、224（小电视）
query_image = cv2.imread("./img/test/emo_8.png")
query_image = cv2.resize(query_image, (256, 256))  # 调整图片大小为统一尺寸
query_feature = calculate_histogram(query_image)

# 计算查询图片与数据库中图片的相似度
scores = []
for feature in database_features:
    score = cv2.compareHist(query_feature, feature, cv2.HISTCMP_INTERSECT)
    scores.append(score)

# 根据相似度排序并输出结果
results = np.argsort(scores)[::-1][:10]  # 降序排列

for i in range(len(results)):
    index = results[i]
    cv2.imshow("Result " + str(i+1), database_images[index])
    cv2.waitKey(0)

cv2.destroyAllWindows()
